package interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UploadFileIterceptor implements HandlerInterceptor {
	private long maxSize;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		if (ServletFileUpload.isMultipartContent(request)) {
			ServletRequestContext context = new ServletRequestContext(request);
			long size = context.getContentLength();
			if (size > maxSize) {
				request.setAttribute("msg", "文件上传过大");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return false;
			}
		}
		///设置拦截器,返回false  请求不在处理,跳转空白页面,设置返回true,进行处理请求
		return true;
	}

	public long getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

}
